package com.homeinns.lyx.server.controller;


import com.homeinns.lyx.server.converter.OrderForm2OrderDTOConverter;
import com.homeinns.lyx.server.dto.OrderDTO;
import com.homeinns.lyx.server.enums.ResultEnum;
import com.homeinns.lyx.server.exception.OrderParamException;
import com.homeinns.lyx.server.form.OrderForm;
import com.homeinns.lyx.server.service.OrderService;
import com.homeinns.lyx.server.utils.ResultVOUtil;
import com.homeinns.lyx.server.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVO<Map<String,String>> createOrder(@Valid OrderForm orderForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new OrderParamException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetails())){
            throw new OrderParamException(ResultEnum.CART_EMPTY);
        }
        OrderDTO result = orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return ResultVOUtil.success(map);
    }
}
